import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/person/entity/soujianren_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';

class MyAddressBloc implements BlocBase {
  List<SouJianRenEntity> _listEntity = [];
  // Stream来处理地址数量
  StreamController<Object> _initController = StreamController<Object>();
  StreamSink<Object> get _initData => _initController.sink;
  Stream<Object> get sendinitData => _initController.stream;

  //  Stream来初始化地址的操作
  StreamController<Object> _initActionController = StreamController<Object>();
  //初始化动作
  StreamSink get initDate => _initActionController.sink;

  //  Stream来设置默认地址的操作
  StreamController<Object> _defaultedController = StreamController<Object>();
  StreamSink get defaultedDate => _defaultedController.sink;

  //  Stream来删除地址的操作
  StreamController<Object> _deleteController = StreamController<Object>();
  StreamSink get deleteDate => _deleteController.sink;

  MyAddressBloc() {
    _initActionController.stream.listen(initAddressData);
    _defaultedController.stream.listen(defaultedAddressData);
    _deleteController.stream.listen(delAddressData);
  }

  void delAddressData(data) {
    if (data is SouJianRenEntity) {
      _delAddressTask(data);
    }
  }

  void defaultedAddressData(data) {
    if (data is String) {
      _setDefaultedAddressTask(data);
    }
  }

  void initAddressData(data) {
    if (data is List && !ObjectUtil.isEmptyList(data)) {
      _listEntity.clear();
      _initData.add(data);
    } else {
      _listEntity.clear();
      _geAddressTask();
    }
  }

  // 删除地址数量
  void _delAddressTask(SouJianRenEntity addressEntity) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.closeAllLoading();
        BotToast.showText(text: '网络无法连接');
      } else {
        BotToast.showLoading();
        Map<String, dynamic> data = {};
        data['userId'] = addressEntity.userId;
        data['souJianRenId'] = addressEntity.id;
        HttpUtilAll.post(Apis.DELETE_ADRESS_LIST_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          BotToast.showText(text: '删除成功');
          _listEntity.remove(addressEntity);
          // BaseConstant.areaListEntity.remove(addressEntity);
          _initData.add(_listEntity);
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  // 初始化地址数量
  void _geAddressTask() async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.closeAllLoading();
        BotToast.showText(text: '网络无法连接');
      } else {
        BotToast.showLoading();
        Map<String, dynamic> data = {};
        data['val'] = BaseConstant.userId;
        HttpUtilAll.post(Apis.MY_ADRESS_LIST_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          // 请求成功返回的数据
          if (null != result) {
            List list = List.from(result);
            for (var item in list) {
              SouJianRenEntity entity = SouJianRenEntity.fromJson(item);
              // entity.isCilke = ('Y' == entity.isDef ? true : false);
              _listEntity.add(entity);
            }
            if (!ObjectUtil.isEmptyList(_listEntity)) {
              BaseConstant.adressEntity = _listEntity[0];
            }

            _initData.add(_listEntity);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  // 初始化地址数量
  void _setDefaultedAddressTask(id) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.closeAllLoading();
        BotToast.showText(text: '网络无法连接');
      } else {
        //   BotToast.showLoading();
        //   Map<String, dynamic> data = {};
        //   data['doUserId'] = BaseConstant.userId;
        //   data['id'] = id;
        //   HttpUtilAll.post(Apis.PERSON_DEFAULTED_ADDRESS_URL,
        //       data: data, headers: {}, success: (result) {
        //     BotToast.closeAllLoading();
        //     // 请求成功返回的数据
        //     if (null != result) {
        //       for (var item in _listEntity) {
        //         if (item.id == id) {
        //           item.isDef = 'Y';
        //         } else {
        //           item.isDef = 'N';
        //         }
        //         item.isCilke = ('Y' == item.isDef ? true : false);
        //       }
        //       BotToast.showText(text: '设置默认银行卡成功');
        //       _initData.add(_listEntity);
        //     }
        //   }, error: (errorMsg) {
        //     BotToast.closeAllLoading();
        //     // 请求失败返回的错误信息
        //     BotToast.showText(text: errorMsg);
        //   });
      }
    });
  }

  @override
  void dispose() {
    _initActionController?.close();
    _initController?.close();
    _defaultedController?.close();
    _deleteController?.close();
  }
}
